package com.learn.cloud.validator.constraints;

import cn.hutool.core.util.ReUtil;
import cn.hutool.core.util.StrUtil;
import com.learn.cloud.validator.annotation.Phone;
import com.learn.cloud.validator.constant.ValidatorConstants;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;

/**
 * @description: 校验手机号是否合法
 * @author: cong zhi
 * @createDate: 2022/2/6 16:06
 * @updateUser: cong zhi
 * @updateDate: 2022/2/6 16:06
 * @updateRemark: 修改内容
 * @version: v1.0
 */
public class PhoneValidator implements ConstraintValidator<Phone, String> {

    private Boolean required;

    @Override
    public void initialize(Phone constraintAnnotation) {
        this.required = constraintAnnotation.required();
    }

    @Override
    public boolean isValid(String phoneValue, ConstraintValidatorContext context) {
        if (StrUtil.isEmpty(phoneValue)) {
            if (required) {
                return false;
            } else {
                return true;
            }
        }
        return ReUtil.isMatch(ValidatorConstants.TEL_REGX, phoneValue);
    }
}
